package com.zja.servlet;


import com.zja.model.JsonResponse;
import com.zja.model.User;
import com.zja.service.Impl.UserServiceImpl;
import com.zja.service.UserService;
import com.zja.util.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
/**
 * @author JA
 * @date: 2025/5/2
 * description:注册
 */
@WebServlet("/api/auth/register")
public class RegisterServlet extends HttpServlet {
    private final UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求和响应的编码格式，防止中文乱码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");


        //从请求中获取参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");

        //获取输出流用于写 JSON 响应
        PrintWriter out = resp.getWriter();

        // 校验验证码
        if (!SendEmailCodeServlet.verifyCode(email, code)) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("验证码错误！"));
            return;
        }

        // 判断用户名是否存在
        if (userService.findByUsername(username) != null) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("用户名已存在！"));
            return;
        }

        // 构建用户对象
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setRole("user");
        user.setCreateTime(new Timestamp(System.currentTimeMillis()));
        user.setUpdateTime(new Timestamp(System.currentTimeMillis()));

        // 注册逻辑
        boolean success = userService.register(user);
        if (success) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.success("注册成功！"));
        } else {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("注册失败，请重试！"));
        }
    }

}
